#include "TreasureRoom.hh"
#include "Item.hh"
#include <iostream>
#include <random>
#include <ctime>
#include "IO.hh"

TreasureRoom::TreasureRoom(const std::string& name, const std::string& text)
    : Room(name, text), opened(false) {}

void TreasureRoom::enterRoom(Player& player) {
    std::cout << "\nYou have entered a mysterious treasure room.\n";
    std::cout << "This is a treasure chest. Opening it might grant you powerful items!\n";

    if (opened) {
        std::cout << "The chest has already been opened.\n";
        return;
    }
while (true)
{
    std::cout << "Do you want to open the treasure chest?\n";
    std::cout << "[1] Open the chest\n[2] Leave\nChoose: ";
    int choice=IO::getNumber();

    if (choice == 1) {
        const std::vector<Item>& allItems = getAllShopItems();

        std::random_device rd; //这是一个随机数种子生成器，用于提供比较随机的种子值。 //This is a random number seed generator that is used to provide a more random seed value.
        std::default_random_engine engine(rd()); //创建一个随机数生成器 engine，使用上面 rd() 生成的种子进行初始化 //Create a random number generator engine and initialize it using the seed generated by rd() above
        //创建一个整数分布对象 dist，其作用是：在 [0, allItems.size() - 1] 范围内随机等概率地生成整数。
        //Create an integer distribution object, dist, which generates integers randomly and equally probably in the range of [0, allItems.size() - 1].
        std::uniform_int_distribution<> dist(0, static_cast<int>(allItems.size() - 1)); 

        //调用分布对象 dist(engine)，生成一个下标值。用这个下标从物品列表 allItems 中取出对应的物品，赋值给 reward。
        //Call the distribution object dist(engine) to generate a subscript value. Use this subscript to take the corresponding item from the item list allItems and assign a value to reward.
        Item reward = allItems[dist(engine)]; 

        std::cout << "\nYou obtained: " << reward.name << " - " << reward.description << "\n";

        if (reward.type == Item::Type::Weapon || reward.type == Item::Type::Armor) {
            player.equipItem(reward);
        } else {
            player.addItem(reward);
        }
        opened = true;
        break;
    } else if(choice==2) {
        std::cout << "You chose not to open the chest.\n";
        break;
    } else {
        std::cout<<"Invalid input.Try again:";
    }
}
}
